package com.cheboohui.iqs.taiping.back;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Element;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cheboohui.iqs.common.basic.StringUtil;
import com.cheboohui.iqs.config.Config;
import com.cheboohui.iqs.http.tool.OkHttp;
import com.cheboohui.iqs.sql.entity.SqlResult;
import com.cheboohui.iqs.taiping.direct.XMLTool;

/**
 * 回调业管处理类
 * 
 * @author xielonghai
 *
 */
public class BackYeGaunDeal {
	/**
	 * logger:日志工具.
	 */
	private static Log log = LogFactory.getLog(BackYeGaunDeal.class);

	/**
	 * 承保回调处理方法
	 * 
	 * @param xml
	 *            回调xml报文
	 */
	public static void contractBack(JSONObject obj, SqlResult dbResult) {
		String value = Config.value + "-承保回调处理";
		log.info(value + "开始...");
		log.info(value + "处理返回报文得到JSON:" + obj);
		if (null == obj || obj.isEmpty()) {
			log.error(value + "回调报文转json处理出错...");
			return;
		}

		if (null == dbResult || !dbResult.isState()) {
			log.error(value + "MYSQL未查询到支付信息");
			return;
		}

		String orderNo = obj.getJSONObject("body").getString("orderNo");
		if (StringUtil.isNulls(orderNo)) {
			log.error(value + "回调报文中订单号为空......");
			return;
		}

		String dbR = JSONObject.toJSONString(dbResult);
		log.info(value + "MYSQL查询得到JSON:" + dbR);
		JSONObject db = JSONObject.parseObject(dbR).getJSONObject("data");
		if (null == db || db.isEmpty()) {
			log.error(value + "MYSQL查询数据错误。。。");
			return;
		}

		String contractBackUrl = db.getString("show_url");// 承保回调地址
		if (StringUtil.isEmpty(contractBackUrl)) {
			log.error(value + "MYSQL查询数据--承保回调地址为空。。。");
			return;
		}

		log.info(value + "-支付回调地址-回调业管承保回调地址:" + contractBackUrl);
		Map<String, String> callback = new HashMap<String, String>();
		callback.put("accountToken", "5AD2975E7EA29B622D59A7CCA57D67CC");
		callback.put("orderNumber", orderNo);// 订单号
		callback.put("paymentTime", db.getString("grade_time"));// 支付发起时间
		// if ("F".equals(obj.getJSONObject("head").getString("status"))) {
		callback.put("paymentStatus", "101");
		callback.put("stateThat", "接收并确认(承保)成功");// 应答信息
		String no = obj.getJSONObject("body").getString("policyNo");
		if (StringUtil.isEmpty(no)) {
			String bNo = obj.getJSONObject("body").getString("businessPolicyNo");
			if (!StringUtil.isEmpty(bNo))
				callback.put("criNumber", bNo);

			String tNo = obj.getJSONObject("body").getString("forcePolicyNo");
			if (!StringUtil.isEmpty(tNo))
				callback.put("insuranceNumber", tNo);

		} else {
			callback.put("criNumber", no);
			callback.put("insuranceNumber", no);
		}

		// } else {
		// callback.put("paymentStatus", "102");
		// callback.put("stateThat", "承保失败");// 应答信息
		// }
		callback.put("paymentType", "201");
		log.info(value + "-承保回调业管系统参数:" + JSONObject.toJSONString(callback));
		log.info(value + "-承保回调业管系统系统返回:" + yewuPost(contractBackUrl, callback));
	}

	/**
	 * 支付回调处理方法
	 * 
	 * @param xml
	 *            回调xml报文
	 */
	public static void payBack(JSONObject obj, SqlResult dbResult) {
		String value = Config.value + "-支付回调处理:";
		log.info(value + "开始..");
		log.info(value + "处理返回报文得到JSON:" + obj);
		if (null == obj || obj.isEmpty()) {
			log.error(value + "回调报文转json处理出错...");
			return;
		}

		if (null == dbResult || !dbResult.isState()) {
			log.error(value + "MYSQL未查询到支付信息");
			return;
		}

		String orderNo = obj.getJSONObject("body").getString("orderNo");
		if (StringUtil.isNulls(orderNo)) {
			log.error(value + "回调报文中订单号为空......");
			return;
		}

		String dbR = JSONObject.toJSONString(dbResult);
		log.info(value + "MYSQL查询得到JSON:" + dbR);
		JSONObject db = JSONObject.parseObject(dbR).getJSONObject("data");
		if (null == db || db.isEmpty()) {
			log.error(value + "MYSQL查询数据错误。。。");
			return;
		}

		String paytBackUrl = db.getString("front_notice");// 支付回调地址
		if (StringUtil.isEmpty(paytBackUrl)) {
			log.error(value + "MYSQL查询数据--支付回调地址为空。。。");
			return;
		}

		log.info(value + "-支付回调地址-回调业管支付回调地址:" + paytBackUrl);

		Map<String, String> callback = new HashMap<String, String>();
		callback.put("accountToken", "5AD2975E7EA29B622D59A7CCA57D67CC");
		callback.put("orderNumber", orderNo);// 订单号
		callback.put("paymentTime", db.getString("grade_time"));// 支付发起时间
		// if ("F".equals(obj.getJSONObject("head").getString("status"))) {
		callback.put("paymentStatus", "101");
		callback.put("stateThat", "接收并确认(支付)成功");// 应答信息
		// } else {
		// callback.put("paymentStatus", "102");
		// callback.put("stateThat", "交易失败");// 应答信息
		// }

		callback.put("paymentType", "201");
		log.info(value + "-支付回调业管系统参数:" + JSONObject.toJSONString(callback));
		log.info(value + "-支付回调业管系统系统返回:" + yewuPost(paytBackUrl, callback));
	}

	/**
	 * 回调业管系统
	 * 
	 * @param yewuUrl
	 * @param orderNo
	 * @return
	 */
	private static String yewuPost(String yewuUrl, Map<String, String> map) {
		try {
			return OkHttp.postByMap(yewuUrl, map);
		} catch (Exception e) {
			return e.getMessage();
		}
	}

	/**
	 * 将回调报文转化为json
	 * 
	 * @param xml
	 * @return
	 */
	public static JSONObject xmlJson(String xml) {
		Element el = XMLTool.toElement(xml);
		if (null == el)
			return null;

		try {
			JSONObject robj = new JSONObject();
			/* head部分报文处理 */
			JSONObject hobj = new JSONObject();
			Element head = (Element) el.getChildren("head").get(0);
			List<?> headList = head.getChildren();
			for (int i = 0; i < headList.size(); i++) {
				hobj.put(((Element) headList.get(i)).getName(), ((Element) headList.get(i)).getValue());
			}
			robj.put("head", hobj);
			/* body部分报文处理 */
			JSONObject bobj = new JSONObject();
			Element body = (Element) el.getChildren("body").get(0);
			List<?> bodyList = body.getChildren();
			for (int i = 0; i < bodyList.size(); i++) {
				bobj.put(((Element) bodyList.get(i)).getName(), ((Element) bodyList.get(i)).getValue());
			}
			robj.put("body", bobj);

			return robj;
		} catch (Exception e) {
			return null;
		}
	}
}
